package com.simba.server.jsonservice.serivces;

import com.simba.common.jsonserver.JsonChannelManager;
import com.simba.common.jsonservice.JsonService;
import com.simba.common.log.LogUtil;
import com.simba.server.ServerParam;
import com.simba.server.components.SortCommonDefines;
import com.simba.server.jsonservice.JsonServiceManager;
import com.simba.server.webservice.WebServiceManager;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ChangeModeJsonService implements JsonService {
    public static final String NAME = "ChangeMode";
    private final static Logger logger = Logger.getLogger(ChangeModeJsonService.class);
    private String remoteAddress = ServerParam.REMOTE_WEBSERVICE_ADDRESS;
    private String localAddress = "http://127.0.0.1:1"+ServerParam.getServerInfo().getJsonServerPort()+"/pcs-tc-nc-job/WyService/services/CommWY?wsdl";
    @Override
    public void handleRequest(Channel channel, Object content) {
        Map<String, Object> map = new HashMap<>();
        map.put(SortCommonDefines.JSON_SERVICE_NAME, "ChangeMode");
        try
        {
            JSONObject request = (JSONObject) content;
            String mode = request.getString("mode");
            if(mode.equals("local"))
            {
                ServerParam.REMOTE_WEBSERVICE_ADDRESS = localAddress;
            }
            else
            {
                ServerParam.REMOTE_WEBSERVICE_ADDRESS = remoteAddress;
            }
            WebServiceManager.getInstance().reset();
            LogUtil.LogInfo(ChangeModeJsonService.logger, "Current Remote Address:"+ServerParam.REMOTE_WEBSERVICE_ADDRESS);
            map.put("Status", true);
        }
        catch (JSONException ex)
        {
            map.put("Status", false);
            LogUtil.LogError(ChangeModeJsonService.logger, "Change Mode Error " + ex.getMessage());
        }finally
        {
            JSONObject jsonObject = new JSONObject(map);
            JsonChannelManager.getInstance().commitResponse(channel, jsonObject.toString().getBytes(), false);
        }
    }
}
